package com.irdstudio.apicenter.mobile.console.service.security;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import com.irdstudio.apicenter.mobile.console.entity.account.VUser;

public class AuthenticationSuccessHandler extends
		SavedRequestAwareAuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws ServletException, IOException {
		Long loginId = writeLog(authentication);
		keepUserInfo(request, authentication, loginId);
		super.onAuthenticationSuccess(request, response, authentication);
	}

	private void keepUserInfo(HttpServletRequest request,
			Authentication authentication, Long loginId) {
		VUser user = (VUser) authentication.getPrincipal();
		user.setLoginId(loginId);
		System.out.println("isadmin="+user.getIsAdmin()+"--isdeveloper="+user.getIsDeveloper()
				+"--username="+user.getUsername()+"--name="+user.getName()+"--id="+user.getId()
				+"--password="+user.getPassword()+"--email="+user.getEmail()+"--status="+user.getStatus()
				+"--isconfiger="+user.getIsConfiger());
		// Map<String, Boolean> opts =
		// vRoleAuthorityManager.loadOperationAuthorityByRole(user.getRoleIds());
		// request.getSession().setAttribute("hasPermission", opts);
		request.getSession().setAttribute("headOffice", user.getHeadOffice());
		request.getSession().setAttribute("branchCode", user.getBranchCode());
		request.getSession().setAttribute("name", user.getName());
		request.getSession().setAttribute("username", user.getUsername());
		request.getSession().setAttribute("isadmin", user.getIsAdmin());
		request.getSession().setAttribute("isdeveloper", user.getIsDeveloper());
		request.getSession().setAttribute("isconfiger", user.getIsConfiger());
	}

	private Long writeLog(Authentication authentication) {
		WebAuthenticationDetails details = (WebAuthenticationDetails) authentication
				.getDetails();
		return new Long(0);
	}

}
